import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import CaptchaImage from '../../src/components/CaptchaImage';

type RootStackParamList = {
  Shouzhao: undefined;
  Xinmi: {
    username?: string;
    from?: 'Youzhao' | 'Shouzhao';
  };
  Daohang: undefined;
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'Shouzhao'>;

const PhoneRecoveryScreen = () => {
  const navigation = useNavigation<NavigationProp>();
  const [phone, setPhone] = useState('');
  const [captcha, setCaptcha] = useState('');
  const [inputCaptcha, setInputCaptcha] = useState('');
  const [isFormValid, setIsFormValid] = useState(false);
  const [captchaError, setCaptchaError] = useState('');
  const [phoneError, setPhoneError] = useState('');
  const [account, setAccount] = useState('');
  const [bindPhone, setBindPhone] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [isSmsBtnDisabled, setIsSmsBtnDisabled] = useState(true);
  const [accountError, setAccountError] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);

  const validateForm = () => {
    const isSmsCodeValid = /^\d{4}$/.test(smsCode);
    if (isSmsCodeValid) {
      setIsVerifying(true);
      // 3秒后激活下一步按钮
      setTimeout(() => {
        setIsFormValid(true);
        setIsVerifying(false);
      }, 3000);
    } else {
      setIsFormValid(false);
      setIsVerifying(false);
    }
  };

  const validatePhone = () => {
    const isPhoneValid = /^1[3-9]\d{9}$/.test(bindPhone);
    setPhoneError(isPhoneValid ? '' : '请输入正确的手机号');
    setIsSmsBtnDisabled(!isPhoneValid);
  };

  const handleCaptchaChange = (newCaptcha: string) => {
    setCaptcha(newCaptcha);
    validateForm();
  };

  const handleSubmit = () => {
    if (isFormValid) {
      navigation.navigate('Xinmi', {
        username: account,
        from: 'Shouzhao'
      });
    }
  };

  const handleBindPhoneChange = (text: string) => {
    setBindPhone(text);
    const isPhoneValid = /^1[3-9]\d{9}$/.test(text);
    setIsSmsBtnDisabled(!isPhoneValid);
    setPhoneError(isPhoneValid ? '' : '请输入正确的手机号');
    validateForm();
  };

  const handleGetSmsCode = async () => {
    if (!/^1[3-9]\d{9}$/.test(bindPhone)) {
      Alert.alert('请输入正确的手机号');
      return;
    }
    try {
      const response = await fetch('http://192.168.78.1:3000/yzm/yzm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: bindPhone })
      });
      const data = await response.json();
      if (data.success) {
        Alert.alert('验证码已发送');
      } else {
        Alert.alert('验证码已发送', data.message || '请注意查收');
      }
    } catch (error) {
      Alert.alert('网络错误', '请检查网络连接');
    }
  };

  const checkAccount = async (username: string) => {
    if (!username) {
      setAccountError('');
      return;
    }

    try {
      const response = await fetch('http://192.168.78.1:3000/users/check-username', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username })
      });

      const data = await response.json();
      
      if (response.status === 404) {
        setAccountError('该账号尚未注册');
      } else if (response.ok) {
        setAccountError('');
        // 如果账号存在，自动填充绑定的手机号
        if (data.data && data.data.phone) {
          setBindPhone(data.data.phone);
          // 更新手机号验证状态和按钮状态
          const isPhoneValid = /^1[3-9]\d{9}$/.test(data.data.phone);
          setPhoneError(isPhoneValid ? '' : '请输入正确的手机号');
          setIsSmsBtnDisabled(!isPhoneValid);
          validateForm();
        }
      } else {
        setAccountError(data.message || '验证失败');
      }
    } catch (error) {
      console.error('验证账号失败:', error);
      setAccountError('网络错误，请重试');
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backBtn} onPress={() => navigation.goBack()}>
          <Text style={styles.backBtnText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>手机找回</Text>
      </View>
      <View style={styles.form}>
        {accountError ? <Text style={styles.errorText}>{accountError}</Text> : null}
        <TextInput
          style={[styles.input, accountError ? styles.inputError : null]}
          placeholder="请输入登录账号"
          placeholderTextColor="#bbb"
          value={account}
          onChangeText={text => {
            setAccount(text);
            validateForm();
          }}
          onBlur={validateForm}
        />
        {phoneError ? <Text style={styles.errorText}>{phoneError}</Text> : null}
        <TextInput
          style={[styles.input, phoneError ? styles.inputError : null]}
          placeholder="请输入与账号绑定的手机号"
          placeholderTextColor="#bbb"
          value={bindPhone}
          onChangeText={handleBindPhoneChange}
          onBlur={validatePhone}
        />
        {captchaError ? <Text style={styles.errorText}>{captchaError}</Text> : null}
        <View style={styles.captchaContainer}>
          <TextInput
            style={[styles.input, styles.captchaInput, captchaError ? styles.inputError : null]}
            placeholder="请输入图形验证码"
            placeholderTextColor="#bbb"
            value={inputCaptcha}
            onChangeText={text => {
              setInputCaptcha(text);
              validateForm();
            }}
            onBlur={validateForm}
          />
          <CaptchaImage onCaptchaChange={handleCaptchaChange} />
        </View>
        <View style={styles.captchaContainer}>
          <TextInput
            style={[styles.input, styles.captchaInput]}
            placeholder="请输入短信验证码"
            placeholderTextColor="#bbb"
            value={smsCode}
            onChangeText={text => {
              const numericValue = text.replace(/[^0-9]/g, '').slice(0, 4);
              setSmsCode(numericValue);
            }}
            onBlur={() => {
              validatePhone();
              validateForm();
            }}
            keyboardType="numeric"
            maxLength={4}
          />
          <TouchableOpacity
            style={[styles.smsBtn, (isSmsBtnDisabled || isVerifying) && styles.smsBtnDisabled]}
            onPress={handleGetSmsCode}
            disabled={isSmsBtnDisabled || isVerifying}
          >
            <Text style={{ color: (isSmsBtnDisabled || isVerifying) ? '#999' : '#fff' }}>
              {isVerifying ? '正在验证...' : '获取验证码'}
            </Text>
          </TouchableOpacity>
        </View>
        <TouchableOpacity 
          style={[styles.submitBtn, !isFormValid && styles.submitBtnDisabled]} 
          onPress={handleSubmit}
          disabled={!isFormValid}
        >
          <Text style={[styles.submitBtnText, !isFormValid && styles.submitBtnTextDisabled]}>
            {isVerifying ? '正在验证...' : '下一步'}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    marginBottom: 10,
    position: 'relative',
  },
  backBtn: {
    position: 'absolute',
    left: 10,
    top: 0,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
    zIndex: 1,
  },
  backBtnText: {
    fontSize: 22,
    color: '#333',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  form: {
    paddingHorizontal: 20,
    flex: 1,
    top: 50,
  },
  input: {
    height: 40,
    backgroundColor: '#f5f5f5',
    borderRadius: 5,
    paddingHorizontal: 10,
    marginBottom: 15,
    fontSize: 14,
  },
  inputError: {
    borderColor: 'red',
    borderWidth: 1,
  },
  captchaContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  captchaInput: {
    flex: 1,
    marginRight: 10,
    marginBottom: 0,
  },
  submitBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  submitBtnDisabled: {
    backgroundColor: '#cccccc',
  },
  submitBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  submitBtnTextDisabled: {
    color: '#666666',
  },
  errorText: {
    color: '#d32f2f',
    fontSize: 12,
    marginBottom: 5,
    marginLeft: 5,
  },
  smsBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 12,
  },
  smsBtnDisabled: {
    backgroundColor: '#cccccc',
  },
});

export default PhoneRecoveryScreen;
